package com.dycong.common.IO.netty.first;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * Created by dycong on 2017/3/13.
 */
public class EchoClient {
    //private static final String host;在指定final变量为static时，就不能在构造里再初始化，加了static时可以在静态代码块初始化一次
//static {
//    host=100+"";
//}
    private final String host;
    private final int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();                //1
            b.group(group)                                //2指定 EventLoopGroup 来处理客户端事件。由于我们使用 com.dycong.common.IO.nio 传输，所以用到了 NioEventLoopGroup 的实现
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)//3使用的 channel 类型是一个用于 com.dycong.common.IO.nio 传输
//                    .remoteAddress(new InetSocketAddress(host, port))    //4设置服务器的 InetSocketAddress
                    .handler(new ChannelInitializer<SocketChannel>() {    //5当建立一个连接和一个新的通道时，创建到 EchoClientHandler 实例添加到 channel pipeline +


                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(
                                    clientHandler);
                        }
                    });
//            while (true)
            ChannelFuture f =  b.connect(new InetSocketAddress(host, port)).sync();        //6连接到远程;等待连接完成

            f.channel().closeFuture().sync();            //7阻塞直到 Channel 关闭

        } finally {
            group.shutdownGracefully().sync();            //8调用 shutdownGracefully() 来关闭线程池和释放所有资源
        }
    }

    private static EchoClientHandler clientHandler = new EchoClientHandler();

    public static void main(String[] args) throws Exception {


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    new EchoClient("localhost", 9090).start();
                }catch (Exception e){

                }
            }
        }).start();// TODO: 2017/4/5 你的Thread不用start吗？？？
        //// TODO: 2017/4/5 handeler中并没有ctx.close()，sokcet未断开，上一句未执行完，自然无法走下一步了。。。。。。放入一个单独的线程来解决
        Scanner scanner = new Scanner(System.in);
        while (clientHandler.sendMsg(scanner.nextLine()));
         ;
    }
}
